package org.aeon.server.handler.Inbound;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.ChatMessage;
import org.aeon.entity.User;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.ChatRequestMessage;
import org.aeon.message.response.ChatResponseMessage;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.Date;

/**
 * @author: MissingAeon
 * @date: 2024/1/26 11:22
 * @description: 消息发送处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        // if(1==1) return;
        final ChatResponseMessage resMsg = new ChatResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final UserDto msgFrom = msg.getFrom();
        final UserDto msgTo = msg.getTo();

        // 目标为自己
        if (msgFrom.equals(msgTo)) {
            resMsg.setResponse(true, "消息");
            resMsg.setMessage(new ChatMessage(msg.getContent(), new Date().getTime(), msgFrom.getId(), msgTo.getId()));
        } else {
            final User user = UserServiceFactory.getService().getUserById(msgTo.getId());
            // 判断目标用户存在
            if (user == null) {
                resMsg.setResponse(false, msgTo.getUsername() + "用户不存在！");
            } else {
                resMsg.setMessage(new ChatMessage(msg.getContent(), msg.getCreationTime().getTime(), msgFrom.getId(), msgTo.getId()));
                log.debug("{} 向 {} 发送了消息", msgFrom.getUsername(), msgTo.getUsername());
                final Channel channel = SessionFactory.getSession().getChannel(user.getId());
                // 判断目标用户在线
                if (channel == null) {
                    // 没有在线
                    resMsg.setResponse(true, "离线消息");
                    UserServiceFactory.getService().addMessageToQueue(user.getId(), resMsg);
                } else {
                    resMsg.setResponse(true, "消息");
                    // 向目标发送
                    channel.writeAndFlush(resMsg);
                }
            }
        }

        // 回应消息
        ctx.writeAndFlush(resMsg);
    }
}
